package webproxy

const (
	TAG_CONFIG = `
[
    {"Find": "head link", "Attr": "href"},
    {"Find": "body a", "Attr": "href"},
    {"Find": "body link", "Attr": "href"},
    {"Find": "body script", "Attr": "src"},
    {"Find": "body script", "Attr": "domain"},
    {"Find": "body video", "Attr": "src"},
    {"Find": "body source", "Attr": "src"},
    {"Find": "head script", "Attr": "src"},
    {"Find": "body img", "Attr": "src"},
    {"Find": "body img", "Attr": "data-src"},
    {"Find": "body area", "Attr": "href"},
    {"Find": "body iframe", "Attr": "src"},
    {"Find": "body form", "Attr": "action"},
    {"Find": "body div", "Attr": "data-src"},
    {"Find":"body include-fragment","Attr": "src"},
    {"Find":"body div","Attr":"data-path"},
    {"Find":"body span","Attr":"data-src"}
]
`
	SCRIPT = `
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!--fuck you cnki -->
	<script>
	var httpVar='%s';
	var httpsVar='%s';
	var reqHost='%s';
    var proxyHost='%s';
    var thaisList;
    function genWhiteList(data){
        thaisList=eval(data);
    }
    </script>
    <script src='%s' async></script>
    <script src='%s' async></script>
    <script>
    (function (open) {
        XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
    
            this.addEventListener("readystatechange", function () {
                if (this.readyState == 1) {
                    console.log(this.readyState, "拦截到的请求链接:", url); // this one I changed
                    url = com.fuck(url, httpVar, httpsVar);
                } else if (this.readyState == 4) {
                    console.log(this.readyState, "实际的请求链接:", url); // this one I changed
                }
            }, false);
            open.call(this, method, url, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);
    </script>
    `
	SCRIPT_BACKUP = `
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!--fuck you cnki -->
	<script>
	var httpVar='%s';
	var httpsVar='%s';
	var reqHost='%s';
    var proxyHost='%s';
    var middle=httpVar.substring(httpVar.indexOf('/'));
    // bind body event DOMNodeInserted DOMSubtreeModified
    document.addEventListener('DOMNodeInserted', function (e) {
        // innerHTML read content
        console.log("插入的节点:", e.target, e.target.tagName);
        com.begin(e.target);
	});
	// document.addEventListener('DOMNodeInserted', function (e) {
    //     // innerHTML read content
    //     console.log("修改的节点:", e.target, e.target.tagName);
    //     com.begin(e.target);
    // });
    var com = new Object();
    com.getFilterList = function () {
        // return lower token
        return [
			{ "img": "src" }, 
			{ "a": "href" }, 
			{ "div": "data-src" },
            { "script": "src" },
            { "span":"data-src"},
            {"link":"href"}
		];
	};
	// backup tag:
	// { "include-fragment": "src" },
	// { "img": "data-src" },//死循环原因
	// { "area": "href" }, 
	// { "iframe": "src" }, 

    com.begin = function (x) {
        // 1.先替换自己
        this.replaceUrl(x);
        // 2.判断是否有孩子,有我就继续处理
        var childs ;
		try{
			childs = x.childNodes;
		}catch(err){
			return;
		}
        // console.log("长度:", childs.length);
        if (childs.length == 0) {
            return;
        } else {
            for (var i = 0, len = childs.length; i < len; i++) {
                // console.log("长度里面:", i, childs[i]);
                if (childs[i].childNodes.length == 0) {
                    com.replaceUrl(childs[i]);
                } else {
                    com.begin(childs[i]);
                }
            }
        }
    };
    com.replaceUrl = function (childNode) {
        myList = this.getFilterList();
        var name;
        try {
            name = childNode.tagName;
        } catch (err) {
            return;
        }

        for (i = 0; i < myList.length; i++) {
            ele = myList[i];
            for (k in ele) {
                if (this.toLower(name) == k) {
					// console.log("Node --> :",ele[k],childNode,childNode.getAttribute(ele[k]));
                    oldVal = childNode.getAttribute(ele[k]);
                    childNode.setAttribute(ele[k], this.fuck(oldVal, httpVar, httpsVar));
                }
            }
        }
    };
    com.toLower = function (str) {
		if (!str){
			return ;
		}
        return str.toLowerCase();
    };
    com.fuck = function (url,fuckUrl,fuckUrl2){
        console.log("In ----> :", url);
        retUrl = com.fucking(url,fuckUrl,fuckUrl2);
        console.log("Out <---- :",retUrl);
        return retUrl;
    }
    com.fucking = function (url, fuckUrl, fuckUrl2) {
        if (!url || url.length < 4) {
            return url;
        }
        finalUrl=fuckUrl;
        thisSchem="http";
		thisLocation=document.location.toString();
		if (thisLocation!="" && thisLocation.substring(0,5)=='https'){
            finalUrl=fuckUrl2;
            thisSchem="https";
		}
		if (url.search(proxyHost)!=-1){
			return url; //有这个域说明处理了
        }else{  //如果没有域，再判断是否有middle 
            if (url.search(middle)!=-1){
                finalHost=finalUrl.substring(0,finalUrl.indexOf('/'));
                return thisSchem+'://'+finalHost+url;
            }
        }
        f4 = url.substring(0, 4);
        f1 = url.substring(0, 1);
        f2 = url.substring(0, 2);
		fn2 = url.substring(1, 2);
		
        if ((f4 == "http") || (f2 == "ws")) {
            strs = url.split('//');
            strLen = strs.length;
            if (strLen > 1) {
                retStr = strs[0].concat('//')
                if (strs[0] == "https:") {
                    retStr = retStr.concat(fuckUrl2);
                } else {
                    retStr = retStr.concat(fuckUrl);
                }
                for (i = 1; i < strLen; i++) {
                    retStr = retStr.concat(strs[i]);
                }
            }
            return retStr;
        } else if ((f1 == '/') && (fn2 != '/')) {
			retStr = '/'.concat(reqHost).concat('/').concat(url.substring(1));
            return retStr;
        } else if (f2 == '//') {
			retStr = '//'.concat(finalUrl).concat('/').concat(url.substring(2));
            return retStr;
        } else {
            return url;
        }
    };
    (function (open) {
        XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {

            this.addEventListener("readystatechange", function () {
                if (this.readyState == 1) {
                    console.log(this.readyState, "拦截到的请求链接:", url); // this one I changed
                    url = com.fuck(url, httpVar, httpsVar);
                } else if (this.readyState == 4) {
                    console.log(this.readyState, "实际的请求链接:", url); // this one I changed
                }
            }, false);
            open.call(this, method, url, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);
	</script>
`
)

// dom tag
type tag struct {
	Find string `json:"Find"`
	Attr string `json:"Attr"`
}

type Config struct {
	Scheme, Addr, Port, OtherAddr, OtherPort, CertPath, KeyPath string
	Script, Middle, Debug                                       string
}

func NewDefaultConfig() Config {
	// create default http config
	return Config{
		Scheme:    "http",
		Addr:      "0.0.0.0",
		Port:      "8080",
		OtherPort: "9090",
		CertPath:  "./cert.pem",
		KeyPath:   "./key.pem",
		Script:    SCRIPT,
		Middle:    `/xxxx/`,
		Debug:     `false`,
	}
}
